from redis.asyncio import Redis, ConnectionPool
from fastapi import Depends
import typing as T

import logging
from .Global import configuration


class AsyncRedisPool:

    def __init__(self):
        config = configuration.redis
        self.pool = ConnectionPool(
            max_connections=config.pool_size,
            host=config.host,
            port=config.port,
            db=config.db,
            password=config.password,
        )
        self.redis = Redis(connection_pool=self.pool, single_connection_client=True)
        self.client = None

    async def __aenter__(self):
        if self.client is None:
            self.client = self.redis
        return self.client

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.client:
            self.client = None


asyncRedisPool = AsyncRedisPool()


async def getRedisSession():
    async with asyncRedisPool as redis:
        async with redis as session:
            yield session


RedisSession = T.Annotated[Redis, Depends(getRedisSession)]

logging.info("redis初始化完成...")
